<template>
  <a-modal
    v-model:open="visible"
    title="数据源配置"
    :footer="null"
    :maskClosable="false"
    style="top: 3rem"
    width="30rem"
    @cancel="onCancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item name="id" label="数据源代码" placeholder="请输入英文小写">
        <a-input v-model:value="formState.id" :disabled="useSign" />
      </a-form-item>
      <a-form-item name="name" label="数据源名称">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item name="type" label="数据源类型">
        <a-select v-model:value="formState.type" placeholder="请选择数据源类型">
          <a-select-option value="Oracle">Oracle</a-select-option>
          <a-select-option value="MySQL">MySQL</a-select-option>
          <a-select-option value="SQLServer">SQLServer</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item name="port" label="端口">
        <a-input v-model:value="formState.port" />
      </a-form-item>
      <a-form-item name="ip" label="IP地址">
        <a-input v-model:value="formState.ip" />
      </a-form-item>
      <a-form-item name="user" label="用户名">
        <a-input v-model:value="formState.user" />
      </a-form-item>
      <a-form-item name="pass" label="密码">
        <a-input-password v-model:value="formState.pass" />
      </a-form-item>
      <a-form-item name="serv" label="服务名">
        <a-input v-model:value="formState.serv" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 16, offset: 10 }">
        <a-button type="primary" style="background: green" @click="onTest">连接测试</a-button>
        <a-button type="primary" style="margin-left: 10px" @click="onSave">保存</a-button>
        <a-button style="margin-left: 10px" @click="onCancel">取消</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, toRaw, watchEffect } from 'vue'
import { useDataBaseStore } from '@/stores/dataBase'
import { DataBaseApi } from '@/api'
import { message } from 'ant-design-vue'

const labelCol = {
  span: 5,
  offset: 2,
}
const wrapperCol = {
  span: 12,
  offset: 1,
}
const dataBaseStore = useDataBaseStore()
const visible = ref(false)
const useSign = ref(false)
const formRef = ref()
const formState = reactive({
  id: '',
  name: '',
  type: '',
  port: '',
  ip: '',
  user: '',
  pass: '',
  serv: '',
})
const rules = reactive({
  id: [
    {
      required: true,
      message: '数据源代码，不允许为空',
      trigger: 'blur',
    },
    {
      pattern: '^[a-z0-9_]*$',
      message: '只能包含英文小写字母、数字、下划线',
      trigger: ['change', 'blur'],
    },
  ],
  name: [
    {
      required: true,
      message: '数据源名称，不允许为空',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: '数据源类型，不允许为空',
      trigger: 'change',
    },
  ],
  port: [
    {
      required: true,
      message: '端口，不允许为空',
      trigger: 'blur',
    },
    {
      pattern: '^[1-9][0-9]*$',
      message: '只允许使用非0开头整数',
      trigger: ['change', 'blur'],
    },
  ],
  ip: [
    {
      required: true,
      message: 'IP地址，不允许为空',
      trigger: 'blur',
    },
  ],
  user: [
    {
      required: true,
      message: '用户名，不允许为空',
      trigger: 'blur',
    },
  ],
  pass: [
    {
      required: true,
      message: '密码，不允许为空',
      trigger: 'blur',
    },
  ],
  serv: [
    {
      required: true,
      message: '服务名，不允许为空',
      trigger: 'blur',
    },
  ],
})

watchEffect(() => {
  if (formState.type == 'Oracle') {
    formState.port = '1521'
  } else if (formState.type == 'MySQL') {
    formState.port = '3306'
  } else if (formState.type == 'SQLServer') {
    formState.port = '1433'
  }
})

let state = 'add'
const showModal = (id) => {
  if (id == null) {
    formState.id = ''
    formState.name = ''
    formState.type = ''
    formState.port = ''
    formState.ip = ''
    formState.user = ''
    formState.pass = ''
    formState.serv = ''
    useSign.value = false
    state = 'add'
  } else {
    DataBaseApi.getOne(id)
      .then((res) => {
        if (res.status == 200) {
          formState.id = res.data.id
          formState.name = res.data.name
          formState.type = res.data.type
          formState.port = res.data.port
          formState.ip = res.data.ip
          formState.user = res.data.user
          formState.pass = res.data.pass
          formState.serv = res.data.serv
          useSign.value = true
          state = 'alt'
          visible.value = true
        } else {
          message.error(res.data)
        }
      })
      .catch((err) => {
        message.error(err.message)
      })
  }
  visible.value = true
}

let testSign = true
const onTest = () => {
  formRef.value.validate().then(() => {
    if (testSign) {
      testSign = false
      DataBaseApi.test(toRaw(formState)).then((res) => {
        if (res == 'success') {
          message.success('数据库连接成功')
          testSign = true
        } else {
          message.error(res)
          testSign = true
        }
      })
    } else {
      message.warning('连接测试中。。。')
    }
  })
}

let saveSign = true
const onSave = () => {
  formRef.value.validate().then(() => {
    if (state == 'add') {
      const dbs = dataBaseStore.getDbs.value
      for (let db of dbs) {
        if (formState.id == db['id']) {
          message.warning(`编码：${db['id']}，已存在，请重新输入`)
          return
        }
      }
    }
    if (saveSign) {
      saveSign = false
      DataBaseApi.save(toRaw(formState)).then((res) => {
        if (res == 'success') {
          let db = {
            id: formState.id,
            ip: formState.ip,
            name: formState.name,
            pass: '',
            port: formState.port,
            serv: formState.serv,
            type: formState.type,
            user: formState.user,
          }
          dataBaseStore.saveDataSource(db)
          message.success('数据源信息，保存成功')
          saveSign = true
          onCancel()
        } else {
          message.error(res)
          saveSign = true
        }
      })
    } else {
      message.warning('已提交，请勿重复提交')
    }
  })
}

const onCancel = () => {
  visible.value = false
  formRef.value.resetFields()
}

defineExpose({ showModal })
</script>

<style></style>
